package com.wiz.web.controllor;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wiz.common.ResponseCode;
import com.wiz.service.HeadquartersService;
import com.wiz.to.HQBaseInfoTO;
import com.wiz.util.MD5Util;
import com.wiz.util.StringUtil;
import com.wiz.vo.CollectionVO;
import com.wiz.vo.ResponResultVO;
import com.wiz.vo.ResponseJsonBody;
import com.wiz.vo.criteria.HqSearchCriteriaTO;

/**
 * 总部
 * @author xxy
 *
 */
@Controller
@RequestMapping("/hq")
public class HeadquartersControllor implements ResponseCode {
	private Gson gson = new GsonBuilder().disableHtmlEscaping().create();
	private transient final Logger log=LoggerFactory.getLogger(getClass());
	@Resource
	private HeadquartersService headquartersService;
	
	@RequestMapping(value="/toAdd")
	public String toAdd(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model){
		
		return "hq/add";
		
	}
	@RequestMapping(value="/toUpdate")
	public String toUpdate(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			HttpSession session, Model model){
		try {
			HQBaseInfoTO baseInfo = headquartersService.gethqsById(hqId);
			model.addAttribute("bean", baseInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "hq/update";
		
	}
	@RequestMapping(value="/add")
	@ResponseBody
	public String add(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqName", required = true) String hqName,
			@RequestParam(value = "registeredName", required = true) String registeredName,
			@RequestParam(value = "registeredNumber", required = true) String registeredNumber,
			@RequestParam(value = "legalRepresentative", required = true) String legalRepresentative,
			@RequestParam(value = "address", required = true) String address,
			@RequestParam(value = "contactsName", required = true) String contactsName,
			@RequestParam(value = "phoneNum", required = true) String phoneNum,
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "loginName", required = true) String loginName,
			@RequestParam(value = "memo", required = false) String memo,
			@RequestParam(value = "provinceId", required = true) String provinceId,
			@RequestParam(value = "province", required = true) String province,
			@RequestParam(value = "cityId", required = true) String cityId,
			@RequestParam(value = "city", required = true) String city,
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        //  获得图片（根据前台的name名称得到上传的文件）   
		MultipartFile hqFile  =  multipartRequest.getFile("hqFile");
		//保存信息
		Date date = new Date();
		HQBaseInfoTO hqBaseInfoTO = new HQBaseInfoTO(0, null, hqName, registeredName, registeredNumber,
				legalRepresentative, address, contactsName, phoneNum, email, 
				null, memo, date, loginName,MD5Util.MD5(phoneNum),
				provinceId, province, cityId, city,date);
		try {
			headquartersService.add(hqBaseInfoTO,hqFile);
			log.info(hqBaseInfoTO.toString());
			 json = new ResponseJsonBody("200", "保存成功", "hq_list",
						"navTab", "closeCurrent", null, null);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			json = new ResponseJsonBody("300", e.getMessage(), "hq_list",
					"navTab", "closeCurrent", null, null);
		}
		return gson.toJson(json);
		
	}
	@RequestMapping(value="/list")
	public String getHqs(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "numPerPage", required = false,defaultValue="10") int pageSize,
			@RequestParam(value = "pageNum", required = false,defaultValue="1") int pageNo,
			@RequestParam(value = "hqName", required = false) String hqName ,//总部名称
			@RequestParam(value = "legalRepresentative", required = false) String legalRepresentative,//法人/代理人
			@RequestParam(value = "contactsName", required = false) String contactsName,//联系人
			@RequestParam(value = "phoneNum", required = false) String phoneNum,//电话
			@RequestParam(value = "provinceId", required = false) String provinceId,
			@RequestParam(value = "cityId", required = false) String cityId,
			HttpSession session, Model model){
		HqSearchCriteriaTO hqSearchCriteriaTO = new HqSearchCriteriaTO(hqName, legalRepresentative,
				contactsName, phoneNum,provinceId,cityId, pageSize, pageNo, (pageNo > 0 && pageSize > 0));
		
		List<HQBaseInfoTO> agentTOs=headquartersService.gethqsByCriteriaTO(hqSearchCriteriaTO);
		int totalCount=headquartersService.gethqsCntByCriteriaTO(hqSearchCriteriaTO);
		CollectionVO collectionTO=new CollectionVO(agentTOs, totalCount, pageSize, pageNo);
		model.addAttribute("collectionTO", collectionTO);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNumShow", totalCount/pageSize+((totalCount%pageSize>0)?1:0));
		model.addAttribute("searchCriteria", hqSearchCriteriaTO);
		
		return "/hq/list";
		
	}
	
	
	
	@RequestMapping(value="/update")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			@RequestParam(value = "hqName", required = true) String hqName,
			@RequestParam(value = "registeredName", required = true) String registeredName,
			@RequestParam(value = "registeredNumber", required = true) String registeredNumber,
			@RequestParam(value = "legalRepresentative", required = true) String legalRepresentative,
			@RequestParam(value = "address", required = true) String address,
			@RequestParam(value = "contactsName", required = true) String contactsName,
			@RequestParam(value = "phoneNum", required = true) String phoneNum,
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "hqFile", required = false) MultipartFile hqFile,
			@RequestParam(value = "memo", required = false) String memo,
			@RequestParam(value = "provinceId", required = true) String provinceId,
			@RequestParam(value = "province", required = true) String province,
			@RequestParam(value = "cityId", required = true) String cityId,
			@RequestParam(value = "city", required = true) String city,
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		HQBaseInfoTO hqBaseInfoTO = new HQBaseInfoTO(0, hqId, hqName, registeredName,
				registeredNumber, legalRepresentative, address, contactsName,
				phoneNum, email, null, memo, null,null,null, provinceId, province, cityId, city,new Date());
		try {
			headquartersService.update(hqBaseInfoTO,hqFile);    
			log.info(hqBaseInfoTO.toString());
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			json = new ResponseJsonBody("300", e.getMessage(), "hq_list",
					"navTab", "closeCurrent", null, null);
			return gson.toJson(json);
		}
		 json = new ResponseJsonBody("200", "修改成功", "hq_list",
				"navTab", "closeCurrent", null, null);
		
		return gson.toJson(json);
		
	}
	@RequestMapping(value="/del")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		try {
			headquartersService.remove(hqId);
			json = new ResponseJsonBody("200","删除成功！" , "hq_list",
					"", "", "", "");
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			json = new ResponseJsonBody("300", e.getMessage(), "hq_list",
					"", "", "", "");
		}
		
		return gson.toJson(json) ;
		
	}
	@RequestMapping(value="/getListHq")
	@ResponseBody
	public String getListHq(HttpServletRequest request,HttpServletResponse response,
	HttpSession session, Model model) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
		List<HQBaseInfoTO> list = null;
		ResponResultVO responResultVO = null;
		try {
			list = headquartersService.getListHq();
			responResultVO = new ResponResultVO(200, "success", 
					list, 0, 0, 0);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			responResultVO = new ResponResultVO(300, e.getMessage(), 
					list, 0, 0, 0);

		}
		log.info(gson.toJson(responResultVO));
		JSONObject json = new JSONObject(responResultVO);
		return json.toString();
		
	}

}
